package com.example.sprinbgbatch.itemreaderxml;

import com.example.sprinbgbatch.itemreaderfile.Customer;
import com.example.sprinbgbatch.itemreaderfile.FlatFileItemWriter;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.validation.BindException;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

//@Configuration
public class XmlItermReaderDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Resource(name = "xmlFileItemWriter")
    private ItemWriter xmlFileItemWriter;

    @Bean
    public Job myXmlItermReaderDemoJob(){
        return jobBuilderFactory.get("myXmlItermReaderDemoJob")
                .start(xmlItermReaderStep())
                .build();
    }

    @Bean
    public Step xmlItermReaderStep() {
        return stepBuilderFactory.get("xmlItermReaderStep")
                .<Customer,Customer>chunk(100)
                .reader(xmlFileItemReader())
                .writer(xmlFileItemWriter)
                .build();
    }
    @Bean
    @StepScope
    public StaxEventItemReader<Customer> xmlFileItemReader() {
        StaxEventItemReader<Customer> reader = new StaxEventItemReader<>();
        reader.setResource(new ClassPathResource("customer.xml"));

        //设置需要处理的根标签
        reader.setFragmentRootElementName("customer");

        //把xml转为对象
        XStreamMarshaller unmarshaller = new XStreamMarshaller();
        Map<String, Class> map = new HashMap<>();
        map.put("customer",Customer.class);
        unmarshaller.setAliases(map);
        reader.setUnmarshaller(unmarshaller);
        return reader;
    }
}
